var express = require('express');
var router = express.Router();
require('express-ws')(router);

router.ws('/', function (ws, req){
  console.log('WebSocket connection established')
  ws.on('message', function (msg) {
    console.log(`receive message ${msg}`)     
  })
  ws.on('close', () => {
    console.log('WebSocket connection closed');
  });
  ws.send('Hello client!')
})


const  users = require('../controllers/users')
router.post('/regist', users.regist)
router.ws('/login',users.login)
router.ws('/regist2', users.regist2)
router.ws('/logon',users.logon)

const  wuser = require('../controllers/wuser')

router.ws('/common',wuser.common)

router.ws('/test', function (ws, req){
  console.log('WebSocket connection established')
  var interval = null
  ws.on('message', function (msg) {
    console.log(`receive message ${msg}`) 
    data = JSON.parse(msg)
    if(data.data=="sign"){
      setTimeout(() => {
        ws.send(msg)
      }, 6000)
    }else if(data.data=="test"){
      ws.send(msg)
      interval = setInterval(()=>ws.send(msg), 10000);
    }
    else    
    ws.send(msg)
  })
  ws.on('close', () => {
    console.log('WebSocket connection closed');
    if(interval)clearInterval(interval)
    interval=null
  });
  ws.send('{"code":0,"data":"Hello client!","info":""}')
})

module.exports = router;
